import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_rider/main/widgets/base/number_layout.dart';
import 'package:flutter_rider/main/widgets/base/pop_pick_spu.dart';
import 'package:flutter_rider/main/widgets/base/task_layout.dart';
import 'package:flutter_rider/main/widgets/dialog/alert_dialog.dart';
import 'package:flutter_rider/main/widgets/dialog/loading_dialog.dart';
import 'package:flutter_rider/main/widgets/ext/u_layout.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/main/widgets/ext/u_title_layout.dart';
import 'package:flutter_rider/main/widgets/state/state_layout.dart';
import 'package:flutter_rider/utils/open_utils.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_rider/module/waybill/page/user_info_page.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/utils/tip.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/utils/log.dart';
import 'package:flutter_svg/svg.dart';
import 'package:flutter_rider/event/click_user_info_event.dart';
import 'package:flutter_rider/generated/r.dart';
import 'package:flutter_rider/event/click_amount_event.dart';

import '../../../api/api.dart';
import 'confirm_order_success.dart';

class ConfirmOrderPage extends StatefulWidget {
  dynamic data;
  ConfirmOrderPage(this.data, {Key? key}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    return ConfirmOrderPageState();
  }
}

class ConfirmOrderPageState extends State<ConfirmOrderPage> {
  final NumberLayoutController _weightLayoutController =
      NumberLayoutController(0);
  final NumberLayoutController _qtyLayoutController = NumberLayoutController(0);
  final TaskLayoutController _taskLayoutController = TaskLayoutController(0);
  late StreamSubscription _eventFn;
  dynamic _data;

  /// 货物类别下标
  var _categoryIndex = 0;

  /// spu的每项的下标
  var _spuKeyIndex = 0;

  /// spu的每项子项的下标
  var _spuValIndex = 0;
  var _unit = 1;
  var _unitName = "";
  int _type = 1;
  List<int> _skuResults = [];

  /// spu的每项内容
  dynamic _jSkuOptions1;
  String fhUserName = "";
  String shUserName = "";
  String fhPhone = "";
  String shPhone = "";
  String fhCarPlate = "";
  String shCarPlate = "";
  String fhAddress = "";
  String shAddress = "";
  String fhLat = "";
  String shLat = "";
  String fhLng = "";
  String shLng = "";
  String fhStationName = "";
  String shStationName = "";
  String fhStationId = "";
  String shStationId = "";
  String fhAliasName = "";
  String shAliasName = "";
  int fhAliasId = 0;
  int shAliasId = 0;
  int skuProductId = 0;
  String skuProductName = "";
  String skuCode = "";
  String spuProductName = "";
  int spuProductId = 0;

  /// 选择中sku_option，包含name,code,val
  var skuOption1 = [];
  int _missionNum = 1;

  @override
  void initState() {
    super.initState();
    _weightLayoutController.decimal = true;
    fhUserName = widget.data["pick_username"];
    shUserName = widget.data["delivery_username"];
    fhPhone = widget.data["pick_tel"];
    shPhone = widget.data["delivery_tel"];
    fhCarPlate = widget.data["pick_car_plate"];
    shCarPlate = widget.data["delivery_car_plate"];
    fhAddress = widget.data["pick_address"];
    shAddress = widget.data["delivery_address"];
    fhAliasName = widget.data["pick_station_alias_name"];
    shAliasName = widget.data["delivery_station_alias_name"];
    fhAliasId = widget.data["pick_station_alias_id"];
    shAliasId = widget.data["delivery_station_alias_id"];
    fhStationName = widget.data["pick_station_name"];
    shStationName = widget.data["delivery_station_name"];
    fhStationId = widget.data["pick_station_id"];
    shStationId = widget.data["delivery_station_id"];
    fhLat = widget.data["pick_lat"];
    shLat = widget.data["delivery_lat"];
    fhLng = widget.data["pick_lng"];
    shLng = widget.data["delivery_lng"];

    _eventFn = eventBus.on<ClickUserInfoEvent>().listen((event) {
      if (_type == 1) {
        setState(() {
          fhLat = event.lat;
          fhLng = event.lng;
          fhStationName = event.stationName;
          fhStationId = event.stationId;
          String stationName = event.aliasName != ""
              ? "(" + event.stationName + ")"
              : event.stationName;
          fhAddress = event.aliasName + stationName;
          fhAliasName = event.aliasName;
          fhAliasId = event.aliasId;
          fhUserName = event.userName;
          fhPhone = event.phone;
          fhCarPlate = event.carPlate;
        });
      } else {
        setState(() {
          shLat = event.lat;
          shLng = event.lng;
          shStationName = event.stationName;
          shStationId = event.stationId;
          String stationName = event.aliasName != ""
              ? "(" + event.stationName + ")"
              : event.stationName;
          shAddress = event.aliasName + stationName;
          shAliasName = event.aliasName;
          shAliasId = event.aliasId;
          shUserName = event.userName;
          shPhone = event.phone;
          shCarPlate = event.carPlate;
        });
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _eventFn.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: UIColor.color_main,
      appBar: UTitleLayout.getBackTitle(context, "确认运单"),
      body: StateLayout(
        url: "/waybill/sku",
        childBuilder: _renderContent,
        dataCallback: _onDataCallback,
      ).padding(EdgeInsets.only(
          left: MediaQuery.of(context).padding.left,
          right: MediaQuery.of(context).padding.right)),
    );
  }

  _onDataCallback(dynamic data) {
    _data = data;
    skuProductId = data[0]["sku_product_id"];
    skuProductName = data[0]["sku_product_name"];
    spuProductName = data[0]["name"];
    _unitName = data[0]["unit_name"];
    spuProductId = data[0]["id"];
    _getSpuResult();
    _getSkuOption1();
    _getSkuCode();
    _setSkuOptions1();
    _reShowMission();
  }

  _getSkuOption1() {
    List<Object> skuOption1Results = [];
    var _options1 = jsonDecode(_data[_categoryIndex]["option1"]);
    for (var i = 0; i < _skuResults.length; i++) {
      // for (var j = 0; j < _options1.length; j++) {
        if (_skuResults[i] != 0) {
          skuOption1Results.add({
            "name": _options1[i]["name"].toString(),
            "code": _options1[i]["code"].toString(),
            "val": _options1[i]["val"][_skuResults[i] - 1].toString()
          });
        }
      // }
    }
    skuOption1 = skuOption1Results;
    for (var i = 0; i < skuOption1.length; i++) {
      for (var j = i + 1; j < skuOption1.length; j++) {
        if (skuOption1[i]["name"] == skuOption1[j]["name"]) {
          skuOption1.removeAt(j);
          // skuOption1.splice(j, 1);
          j--;
        }
        ;
      }
      ;
    }
    ;
  }

  /// 根据选择的项和数量来获取对应的sku
  _getSkuCode() {
    List arr = jsonDecode(_data[_categoryIndex]["option3"])["values"];
    List array = jsonDecode(_data[_categoryIndex]["option1"]);

    for (var i = 0; i < arr.length; i++) {
      int _account = 0;

      for (var z in arr[i].values) {
        for (var j = 0; j < _skuResults.length; j++) {
          if (z == array[j]["val"][_skuResults[j] - 1]) {
            _account += 1;
          }
        }
      }
      // 按件计费
      if (_unit == 1 && arr[i]["section"] != null) {
        num _qty = _qtyLayoutController.number;
        bool flag = _qty >= jsonDecode(arr[i]["section"])[0] &&
            _qty <= jsonDecode(arr[i]["section"])[1];
        if (_account == _skuResults.length && flag) {
          skuCode = arr[i]["SKU"];
        }
      } else {
        if (_account == _skuResults.length) {
          skuCode = arr[i]["SKU"];
        }
      }
    }
  }

  /// 获取选中结果下标
  _getSpuResult() {
    // 先初始化，避免脏数据
    _skuResults = [];
    List arr = jsonDecode(_data[_categoryIndex]["option1"]);
    // 根据option1的长度确定
    for (var i = 0; i < arr.length; i++) {
      // 默认是第一个
      _skuResults.add(1);
    }
  }

  /// 切换获取类别的时候，更新下spu每一项
  _setSkuOptions1() {
    _jSkuOptions1 = jsonDecode(_data[_categoryIndex]["option1"]);
  }

  _reShowMission() {
    var jSkuOptions3 = jsonDecode(_data[_categoryIndex]["option3"]);
    var valuesList = jSkuOptions3["values"];
    valuesList.asMap().keys.map((index) {
      Log.i(index);
      var SKU = valuesList[index]["SKU"];
      if (SKU == skuCode) {
        num car_load = valuesList[index]["car_load"];
        num qty = _qtyLayoutController.number == null
            ? widget.data['qty']
            : _qtyLayoutController.number;
        num result = qty / car_load;
        _missionNum = result.ceil();
        setState(() {
          _missionNum = _missionNum;
          _taskLayoutController.number = _missionNum;
        });
        eventBus.fire(ClickAmountEvent(_missionNum));
      }
    }).toList();
  }

  Widget _renderContent(dynamic data) {
    return Column(
      children: [
        Expanded(
          child: SingleChildScrollView(
            child: Column(
              children: [
                _renderNo(),
                Container(height: 0.5.rpx, color: UIColor.color_divider),
                _renderShop(),
                10.hspace,
                _renderSendAndRecv(),
                10.hspace,
                _renderSKU(),
                10.hspace,
                _renderTask(),
                10.hspace,
              ],
            ),
          ),
        ),
        Padding(
          padding: EdgeInsets.all(12.rpx),
          child: UText.getBkButton(
            "提交",
            16.rpx,
            bkColor: UIColor.color_primary,
            radius: 12.rpx,
            width: double.infinity,
            height: 48.rpx,
            onPressed: _onClickSubmit,
          ),
        ),
        SizedBox(height: MediaQuery.of(context).padding.bottom),
      ],
    );
  }

  Widget _renderNo() {
    return Container(
      height: 48.rpx,
      padding: EdgeInsets.symmetric(horizontal: 16.rpx),
      decoration: const BoxDecoration(
        color: UIColor.color_content,
      ),
      child: Row(
        children: [
          SizedBox(
                  width: 80.rpx,
                  child: UText.get("运单编号", UIColor.color_t5, 16.rpx))
              .expand,
          Row(children: [
            UText.get(widget.data["waybill_no"], UIColor.color_t1, 16.rpx),
            4.wspace,
            GestureDetector(
              onTap: () {
                Clipboard.setData(
                    ClipboardData(text: widget.data["waybill_no"]));
                Tip.show("已复制到剪贴板");
              },
              child: SvgPicture.asset(
                R.image_text_copy,
                width: 16.rpx,
                height: 16.rpx,
              ),
            ),
          ])
        ],
      ),
    );
  }

  Widget _renderShop() {
    return Container(
      height: 48.rpx,
      padding: EdgeInsets.symmetric(horizontal: 16.rpx),
      decoration: const BoxDecoration(
        color: UIColor.color_content,
      ),
      child: Row(
        children: [
          SizedBox(
                  width: 80.rpx,
                  child: UText.get("店铺名称", UIColor.color_t5, 16.rpx))
              .expand,
          UText.get(widget.data["merchant_name"], UIColor.color_t1, 16.rpx),
        ],
      ),
    );
  }

  Widget _renderSendAndRecv() {
    return Container(
        padding: EdgeInsets.symmetric(horizontal: 12.rpx, vertical: 12.rpx),
        decoration: const BoxDecoration(
          color: UIColor.color_content,
        ),
        child: Column(
          children: [
            _consigneeInfo(),
            10.hspace,
            _deliverInfo(),
          ],
        ));
  }

  Widget _consigneeInfo() {
    return GestureDetector(
        onTap: () {
          _type = 1;
          OpenUtils.open(
              context,
              UserInfoPage(
                  fhUserName,
                  fhPhone,
                  fhAddress,
                  fhCarPlate,
                  fhLat,
                  fhLng,
                  fhStationName,
                  fhStationId,
                  fhAliasName,
                  fhAliasId,
                  1));
        },
        child: Container(
          width: 350.rpx,
          height: 76.rpx,
          decoration: BoxDecoration(
            color: UIColor.color_input,
            borderRadius: BorderRadius.circular(8.rpx),
          ),
          child: Row(
            children: [
              10.wspace,
              SvgPicture.asset(R.image_send, width: 24.rpx, height: 24.rpx),
              6.wspace,
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    UText.get(fhAddress, UIColor.color_t1, 16.rpx,
                        overflow: TextOverflow.ellipsis),
                    5.hspace,
                    UText.get(fhUserName + "   " + fhPhone + "   " + fhCarPlate,
                        UIColor.color_t5, 12.rpx,
                        overflow: TextOverflow.ellipsis),
                  ],
                ),
              ),
            ],
          ),
        ));
  }

  Widget _deliverInfo() {
    return GestureDetector(
        onTap: () {
          _type = 2;
          OpenUtils.open(
              context,
              UserInfoPage(
                  shUserName,
                  shPhone,
                  shAddress,
                  shCarPlate,
                  shLat,
                  shLng,
                  shStationName,
                  shStationId,
                  shAliasName,
                  shAliasId,
                  2));
        },
        child: Container(
          width: 350.rpx,
          height: 76.rpx,
          decoration: BoxDecoration(
            color: UIColor.color_input,
            borderRadius: BorderRadius.circular(8.rpx),
          ),
          child: Row(
            children: [
              10.wspace,
              SvgPicture.asset(R.image_get, width: 24.rpx, height: 24.rpx),
              6.wspace,
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    UText.get(shAddress, UIColor.color_t1, 16.rpx,
                        overflow: TextOverflow.ellipsis),
                    5.hspace,
                    UText.get(shUserName + "   " + shPhone + "   " + shCarPlate,
                        UIColor.color_t5, 12.rpx,
                        overflow: TextOverflow.ellipsis),
                  ],
                ),
              ),
            ],
          ),
        ));
  }

  Widget _renderSKU() {
    return Container(
      decoration: const BoxDecoration(
        color: UIColor.color_content,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _renderSpuType(),
          ..._jSkuOptions1.asMap().keys.map((index) {
            return _renderOneSku(index);
          }).toList(),
          _renderTotalWeight(),
          Container(
              margin: EdgeInsets.only(left: 16.rpx, top: 10.rpx, right: 16.rpx),
              height: 0.5.rpx,
              color: UIColor.color_divider),
          10.hspace,
          _renderQty(),
          6.hspace,
        ],
      ),
    );
  }

  Widget _renderSpuType() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      child: Container(
        height: 48.rpx,
        padding: EdgeInsets.symmetric(horizontal: 16.rpx),
        child: Row(
          children: [
            UText.get("货物类别", UIColor.color_t1, 16.rpx, fw: FontWeight.w600),
            16.wspace,
            UText.get(
                _data[_categoryIndex]["name"] ?? "", UIColor.color_t1, 14.rpx),
            const Spacer(),
            Icon(Icons.navigate_next, size: 20.rpx, color: UIColor.color_t3),
          ],
        ),
      ),
      onTap: () {
        // 选择货物类别
        OpenUtils.pop(
            context,
            PopPickSpu(
              list: _data,
              nameKey: "name",
              initItem: _categoryIndex,
              callback: (index) {
                setState(() {
                  _categoryIndex = index;
                  _spuKeyIndex = 0;
                  _spuValIndex = 0;
                  _unit = _data[_categoryIndex]["unit"];
                  _unitName = _data[_categoryIndex]["unit_name"];
                  skuProductId = _data[_categoryIndex]["sku_product_id"];
                  skuProductName = _data[_categoryIndex]["sku_product_name"];
                  spuProductName = _data[_categoryIndex]["name"];
                  spuProductId = _data[_categoryIndex]["id"];
                });
                // var len = jsonDecode(_data[_spuIndex]["option1"]).length;
                // if(len == 1) {
                //   _skuResults = [1,0];
                // } else if(len == 2){
                //   _skuResults = [1,1,0];
                // } else if(len == 3) {
                //   _skuResults = [1,1,1,0];
                // }
                _getSpuResult();
                // _reShowSku();
                _getSkuOption1();
                _reShowMission();
                _setSkuOptions1();
                _getSkuCode();
              },
            ));
      },
    );
  }

  Widget _renderOneSku(int index) {
    var sku = _jSkuOptions1[index];
    var list = sku["val"] as List;
    return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Container(
          margin: EdgeInsets.symmetric(horizontal: 16.rpx),
          height: 0.5.rpx,
          color: UIColor.color_divider),
      16.hspace,
      Padding(
        padding: EdgeInsets.symmetric(horizontal: 16.rpx),
        child: UText.get(sku["name"], UIColor.color_t1, 16.rpx,
            fw: FontWeight.w600),
      ),
      12.hspace,
      Padding(
        padding: EdgeInsets.symmetric(horizontal: 16.rpx),
        child: Wrap(
          spacing: 10.rpx,
          runSpacing: 0.rpx,
          children: list
              .asMap()
              .keys
              .map((valIndex) => _renderOneSkuVal(sku, index, valIndex))
              .toList(),
        ),
      ),
      16.hspace,
    ]);
  }

  Widget _renderOneSkuVal(dynamic sku, int index, int valIndex) {
    var isSelect = valIndex == _skuResults[index] - 1;
    return UText.getBkButton(
      sku["val"][valIndex],
      14.rpx,
      color: isSelect ? Colors.white : UIColor.color_t3,
      width: 50.rpx,
      height: 32.rpx,
      radius: 8.rpx,
      bkColor: isSelect ? UIColor.color_primary : UIColor.color_input,
      padding: EdgeInsets.symmetric(horizontal: 12.rpx),
      onPressed: () {
        // spu的每项子项的下标
        setState(() {
          _spuKeyIndex = index;
          _spuValIndex = valIndex;
        });
        // spu的每项子项的下标,更新选择下标的结果
        _skuResults[_spuKeyIndex] = _spuValIndex + 1;
        _getSkuOption1();
        _reShowMission();
        _setSkuOptions1();
        _getSkuCode();
      },
    );
  }

  Widget _renderTotalWeight() {
    Widget rw;
    if (_unit == 1) {
      rw = 0.wspace;
    } else {
      rw = Container(
          padding: EdgeInsets.fromLTRB(0, 10.rpx, 0, 0),
          margin: EdgeInsets.fromLTRB(16.rpx, 0, 16.rpx, 0),
          decoration: const BoxDecoration(
            border: Border(
                top: BorderSide(width: 0.5, color: UIColor.color_divider)),
          ),
          child: Row(
            children: [
              UText.get("数量（吨）", UIColor.color_t1, 16.rpx, fw: FontWeight.w600),
              const Spacer(),
              NumberLayout(
                  controller: _weightLayoutController,
                  initNumber: 1,
                  max: 10000,
                  editParentText: () => {
                        setState(() {
                          //_choose = 2;
                        })
                      }),
            ],
          ));
    }
    return rw;
  }

  Widget _renderQty() {
    return Row(
      children: [
        16.wspace,
        UText.get("件数（件）", UIColor.color_t1, 16.rpx, fw: FontWeight.w600),
        const Spacer(),
        NumberLayout(
            controller: _qtyLayoutController,
            initNumber: widget.data['qty'],
            max: 10000,
            editParentText: () => {_reShowMission(), _getSkuCode()}),
        16.wspace,
      ],
    );
  }

  Widget _renderTask() {
    return Container(
        height: 48.rpx,
        padding: EdgeInsets.symmetric(horizontal: 16.rpx),
        decoration: const BoxDecoration(
          color: UIColor.color_content,
        ),
        child: Row(
          children: [
            UText.get("任务数量", UIColor.color_t1, 16.rpx, fw: FontWeight.w600),
            const Spacer(),
            TaskLayout(
                controller: _taskLayoutController,
                initNumber: _missionNum,
                max: 100,
                editParentText: () => {}),
          ],
        ));
  }

  _onClickSubmit() {
    if (shAddress == "" || shUserName == "" || shPhone == "") {
      Tip.show("请完善收货信息");
      return;
    }
    if (_weightLayoutController.number == 0 && _unit == 2) {
      Tip.show("请输入数量");
      return;
    }
    if (_qtyLayoutController.number == 0) {
      Tip.show("请输入件数");
      return;
    }
    if (_taskLayoutController.number == 0) {
      Tip.show("请输入任务数量");
      return;
    }
    CustomAlertDialog.show(context,
        title: "确认提交吗？",
        content: "确认后将对运单进行分配车辆。",
        confirmText: "确认提交", onConfirm: () {
      var dialog = LoadingDialog(context);
      dialog.show(text: "提交中...");
      var json = _getPostJson();
      Log.i(json);
      var url = "/waybill/confirm";
      dialog.hide();
      Api.submitx(context, url,
          data: json,
          progress: false,
          success: (data) {
            dialog.hide();
            OpenUtils.open(
                context, ConfirmOrderSuccessPage(1, widget.data["waybill_no"]));
          },
          failTip: "提交失败",
          fail: (_) {
            dialog.hide();
          });
    });
  }

  dynamic _getPostJson() {
    var json = {};
    json["waybill_no"] = widget.data["waybill_no"];

    json["pick_lng"] = fhLng;
    json["pick_lat"] = fhLat;
    json["pick_username"] = fhUserName;
    json["pick_tel"] = fhPhone;
    json["pick_car_plate"] = fhCarPlate;
    json["pick_station_alias_id"] = fhAliasId;
    json["pick_station_alias_name"] = fhAliasName;

    json["delivery_lng"] = shLng;
    json["delivery_lat"] = shLat;
    json["delivery_station_id"] = shStationId;
    json["delivery_station_name"] = shStationName;
    json["delivery_username"] = shUserName;
    json["delivery_tel"] = shPhone;
    json["delivery_address"] = shAddress;
    json["delivery_car_plate"] = shCarPlate;
    json["delivery_station_alias_id"] = shAliasId;
    json["delivery_station_alias_name"] = shAliasName;

    json["spu_product_id"] =
        spuProductId == 0 ? widget.data["spu_product_id"] : spuProductId;
    json["sku_code"] = skuCode == "" ? widget.data["sku_code"] : skuCode;
    json["sku_product_id"] =
        skuProductId == 0 ? widget.data["sku_product_id"] : skuProductId;
    json["sku_product_name"] =
        skuProductName == "" ? widget.data["sku_product_name"] : skuProductName;
    json["spu_product_name"] =
        spuProductName == "" ? widget.data["spu_product_name"] : spuProductName;
    json["sku_option"] = skuOption1.isEmpty
        ? widget.data["sku_option1"]
        : jsonEncode(skuOption1);
    json["mission_num"] = _taskLayoutController.number > 0
        ? _taskLayoutController.number
        : widget.data["mission_num"];
    json["unit"] = _unit > 0 ? _unit : widget.data["unit"];
    json["unit_name"] = _unitName == "" ? widget.data["unit_name"] : _unitName;

    var weight = _weightLayoutController.number;
    var qty = _qtyLayoutController.number;
    if (_unit == 2) {
      json["weight"] = (weight * 1000).toInt();
    }
    json["qty"] = qty.toInt();
    Log.i(json);
    return json;
  }
}
